import * as types from './mutation-types'
import {storageKey} from '@/utils/constant.js'

import * as userAPI from '@/api/user.js'
import * as cache from '@/utils/storage.js'
import {jumpTo,getClientInfo,bindAlias} from "@/utils/util.js"
import {unauthPath} from "@/utils/constant.js"
import DC,{initDC} from "@/DC/index.js"
import { User } from '@/entity/User'
// #ifdef APP-PLUS
import { pathByUrl,downToPath } from "@/services/mediaService"
// #endif
let timer = null
export default {
	async initUser({commit,dispatch,rootState}){
		const token = await cache.get(storageKey.token)
		if(!token){
			throw '缓存中暂无登录对象'
		}
		commit(types.UPDATE_TOKEN,token)
		const userInfo = await dispatch('fetchUserInfo');
		initDC(userInfo.userId)
		
		
		if(rootState.chat){
			dispatch('chat/loginChat',userInfo.userId,{ root: true })
		}
		if(rootState.wallet){
			dispatch('wallet/initWallet',undefined,{ root: true })
		}
		if(rootState.addr){
			dispatch('addr/init',undefined,{ root: true })
			dispatch('addr/fetchPendApplyCount',undefined,{ root: true })
			
			timer = setInterval(()=>{
				dispatch('addr/fetchPendApplyCount',undefined,{ root: true })
				
			},3000)
		}
		if(rootState.face){
			dispatch('face/initFace',undefined,{ root: true })
		}
		
		
		
		return {token,userInfo}
	},
	async login({commit,dispatch,rootState},{token,userInfo}){
		commit(types.UPDATE_TOKEN,token)
		commit(types.UPDATE_USER_INFO,userInfo)
		getClientInfo().then(async ({clientid}={})=>{
			console.log('clientid',clientid)
			const systemInfo = getApp().globalData.systemInfo
			userAPI.reportDevice({pushId:clientid,...systemInfo,event:'login'})
			// #ifdef APP-PLUS
			bindAlias(userInfo.userId)
			console.log("绑定别名完毕")
			// #endif
		}).catch((e)=>{
			console.error(e)
		})
		initDC(userInfo.userId)
		const self = User.creatNullIns({...userInfo})
		DC.userDB.setUser(self)
		await cache.set(storageKey.token,token)
		await cache.set(storageKey.sessionUserInfo,userInfo)
		await cache.set(storageKey.userId,userInfo.userId)
		if(rootState.chat){
			dispatch('chat/loginChat',userInfo.userId,{ root: true })
		}
		if(rootState.wallet){
			dispatch('wallet/initWallet',undefined,{ root: true })
		}
		if(rootState.addr){
			dispatch('addr/init',undefined,{ root: true })
			dispatch('addr/fetchPendApplyCount',undefined,{ root: true })
			
			timer = setInterval(()=>{
			 	dispatch('addr/fetchPendApplyCount',undefined,{ root: true })
			 	
			},3000)
		}
		
		
		
		return {token,userInfo}
	},
	async logout({commit,dispatch,rootState}){
		try{
			await userAPI.logout()
		}catch(e){
			console.log('登出接口调用失败')
		}
		commit(types.UPDATE_TOKEN,'')
		commit(types.UPDATE_USER_INFO,null)
		commit(types.UPDATE_REAL,null)
		commit(types.UPDATE_PETS,[])
		commit('mixUnread',{
			praiseCount:0, 
			commentCount:0, 
			fansCount:0 
		})
		if(rootState.chat){
			dispatch('chat/logoutChat',undefined,{ root: true })
		}
		if(rootState.wallet){
			dispatch('wallet/clear',undefined,{ root: true })
		}
		if(rootState.addr){
			dispatch('addr/clear',undefined,{ root: true })
			clearInterval(timer)
		}
		await cache.remove(storageKey.token)
		await cache.remove(storageKey.sessionUserInfo)
		await cache.remove(storageKey.userId)
	},
	async fetchUserInfo({commit,dispatch}){
		const userInfo = await userAPI.getUserInfo()
		if(DC.userDB){
			const self = DC.userDB.getUser(userInfo.userId)
			self.mixIns(User.origin2Ins(userInfo))
			// #ifdef APP-PLUS
			userInfo.saveAvatar=''
			pathByUrl(self.avatarUrl).then((path)=>{
				if(path){
					self.saveAvatar = path
					userInfo.saveAvatar = path
				}else{
					downToPath(self.avatarUrl).then((newPath)=>{
						self.saveAvatar = newPath
						userInfo.saveAvatar = newPath
					})
				}
			})
			// #endif
		}
		commit(types.UPDATE_USER_INFO,userInfo)
		await cache.set(storageKey.sessionUserInfo,userInfo)
		return userInfo
	},
	async fetchPets({commit}){
		const list = await petAPI.getMyPets()
		commit(types.UPDATE_PETS,list)
	},
	
	async signIn({commit,state:{sign}}){
		const res = await userAPI.sign()
		commit(types.UPDATE_SIGN,{
			...sign,
			sign:true
		})
		return res
	},
	async fetchSign({commit,state,...rest}){
		console.log(rest)
		const res = await userAPI.isSign()
		commit(types.UPDATE_SIGN,res)
		return res
	},
	async fetchUnread({commit}){
		const res = await getUnread()
		commit('mixUnread',res)
		return res
	},
	authJump({getters},{url,type}){
		if(getters.isLogin){
			return jumpTo(url,type)
		}else{
			return jumpTo(unauthPath)
		}
	},
	mixUser({getters,commit},user){
		const userInfo = {
			...getters.userInfo,
			...user
		}
		commit(types.UPDATE_USER_INFO,userInfo)
		cache.set(storageKey.sessionUserInfo,userInfo)
	}
}
